import { Upload, Button, Divider, Dropdown, Form, Icon, Menu, message, Avatar, Table, PageHeader, Tooltip, Input } from 'antd';
import React, { useState, useEffect } from 'react';
import CreateForm from './CreateForm';
import { createApiRule, deleteApiRule, findApiRule } from '../service';
import styles from '../index.less';
import request from '@/utils/request';
import { HTTP_STATUS, MAX_UPLOAD_SIZE, VDISK_NAME } from "@/generic/ConfigParams";

const { Search } = Input;
const ButtonGroup = Button.Group;

export const filesUpload = (opts, vdiskName, currentPath, tableRefresh) => {

    const hide = message.loading('正在上传，请稍候。');
    const fileName = opts.file.name;
    const reader = new FileReader();
    reader.readAsArrayBuffer(opts.file);
    reader.onload = async e => {
        const response = await request(`/disk/${vdiskName}${currentPath}/${fileName}`, {
            method: 'post',
            data: e.target.result,
            headers: {
                'Authorization': `Bearer ${localStorage.getItem("token")}`
            },
            parseResponse: false,
        })
        hide();
        if (response.ok) {
            message.success(`${fileName} 上传成功！`);
            tableRefresh();
        }
        else {
            message.error(`${fileName}上传失败：${HTTP_STATUS[response.status]}！`);
        }
    }
}

export const beforeUpload = (file, _) => { // 此处做文件的大小检查与限制

    if (file.size > MAX_UPLOAD_SIZE.size) {
        message.warn(`文件不得超过${MAX_UPLOAD_SIZE.format}！`);
        return false;
    }
}

export const deleteOpt = (rows, vdiskName, tableRefresh) => {
    console.log("===>>>>>-------------->> rows", rows, vdiskName)
        let hide = message.loading("删除中...")
        rows.forEach(async item => {

            const response = await deleteApiRule({ disk: vdiskName, location: item.path });
            hide();
            if (response.ok) {
                tableRefresh();
                return;
            }
            message.error(`${HTTP_STATUS[response.status]}`);
        })
}

class OptsHeader {

    constructor(vdisk, path, tableRefresh){
        this.vdiskName = vdisk();
        this.currentPath = path;
        this.tableRefresh = tableRefresh;
    }

    uploadProps = {
        key: "0",
        className: styles.headerUpload,
        // accept: "text/*,application/*,image/*",  // 更多参考：https://www.iana.org/assignments/media-types/media-types.xhtml
        showUploadList: false,
        beforeUpload,
        customRequest: (opts) => filesUpload(opts, this.vdiskName, this.currentPath, this.tableRefresh)
    };

    handleCreate = async (fields) => {

        const hide = message.loading('正在添加');
        console.log("==>> fields", fields, this.currentPath)
        if (this.vdiskName == 'usr' && this.currentPath == '/') {
            this.currentPath = `/${VDISK_NAME}`
        }
        try {
            let _response = await createApiRule({
                disk: this.vdiskName,
                location: `${this.currentPath}/${fields.value}`,
            })
            if (_response) {
                if (!_response.ok) {
                    hide();
                    return false;
                }
            }
            else {
                hide();
                message.success('添加成功');
                return true;
            }
        } catch (error) {
            hide();
            message.error('添加失败请重试！');
            return false;
        }
    }

    titleRender = (opts = null, batchOpts = {show:false, rows: []}) => {
        return [
            <Upload {...this.uploadProps} >
                <Button className={styles.headerBtns} icon="upload" type="primary" >上传</Button>
            </Upload>,
            <Button key="1" className={styles.headerBtns} icon="plus" type="" onClick={() => opts.setModalVisible(true)}>目录</Button>,
            batchOpts.show && (
                <ButtonGroup key="2">
                    <Button icon="delete" onClick={() => this.deleteOption(batchOpts.rows)}>删除</Button>
                    <small key="3" style={{ marginLeft: "8px", fontSize: "60%", fontWeight: 200, }}>
                        已选择&nbsp;
                        <a style={{ fontWeight: 400, }} >
                            {batchOpts.rows.length}
                        </a>
                        &nbsp;项
                    </small>
                </ButtonGroup>
                    
            ),

        ];
    }

    deleteOption = (rows) => deleteOpt(rows, this.vdiskName, this.tableRefresh);

    propFind = async (value, onSearch) => {

        const hide = message.loading("正在查询，请稍候。")
        const params = {
            value: value,
            deepth: 1,
        };
        const response = await findApiRule(params, this.vdiskName, this.currentPath);
        // console.log("===>> propFind", response)
        if (response.ok) {
            hide();
            const content = await response.json();
            onSearch(new Promise((resolve) => {
                resolve(content.items);
            }))
            return;
        }
        console.error("查询失败。", response.status )
        message.error("查询失败。请重新输入查询条件！")
    }
}

const OptionsHeader = props => {

    const { className, batchOpts, currentPath, vdisk, tableRefresh, onSearch } = props;
    const [modalVisible, setModalVisible] = useState(false);
    const [title, setTitle] = useState('');
    const optsHeader = new OptsHeader(vdisk, currentPath, tableRefresh);

    useEffect(()=> {
        // console.log("===---------->> batchOpts", batchOpts, currentPath)
        setTitle(optsHeader.titleRender({ setModalVisible }, batchOpts, tableRefresh));
    }, [batchOpts, currentPath])

    const extraRender = () => {

        return [
            <Search
                key="0"
                placeholder="输入搜索内容"
                onSearch={(value) => {
                    optsHeader.propFind(value, onSearch)
                }}
            />,
        ];
    }

    return (
        <>
            <PageHeader
                title={title}
                extra={extraRender()}
                className={className}
            />
            <CreateForm
                onSubmit={async value => {
                    const success = await optsHeader.handleCreate(value);

                    if (success) {
                        setModalVisible(false);
                        tableRefresh();
                    }
                }}
                onCancel={() => setModalVisible(false)}
                modalVisible={modalVisible}
            />
        </>
    )
}

export default Form.create()(OptionsHeader);